package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 2018/5/29
 */
class BiomFileDataDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import utils.MyPostgresProfile.api._

  type MyRow = BiomFileDataRow
  val table = BiomFileData

  def selectAllFileName(userId: Int) = db.run(table.
    filter(x => x.userId === userId).map(_.fileName).result.map(_.toList))

  def insert(row: MyRow): Future[Unit] = db.run(table += row).map(_ => ())

  def selectAll(userId: Int) = db.run(table.
    filter(x => x.userId === userId).sortBy(_.id.desc).result)

  def select(userId: Int, fileName: String) = db.run(table.
    filter(x => x.userId === userId).filter(_.fileName === fileName).result.head)

  def select(id: Int) = db.run(table.
    filter(x => x.id === id).result.head)

  def selectAll(ids: List[Int]) = db.run(table.filter(x => x.id.inSetBind(ids)).result.map(_.toList))

  def selectAll = db.run(table.result.map(_.toList))

  def delete(userId: Int, id: Int): Future[Unit] = db.run(table.filter(_.userId === userId).filter(_.id === id).
    delete).map(_ => ())

  def deletes(userId: Int, ids: List[Int]): Future[Unit] = db.run(table.filter(_.userId === userId).
    filter(_.id.inSetBind(ids)).delete).map(_ => ())

  def update(row: MyRow): Future[Unit] = db.run(table.filter(_.id === row.id).update(row)).
    map(_ => ())

  def updates(rows: Seq[MyRow]): Future[Unit] = {
    val action = {
      val ids = rows.map(_.id)
      val delete = table.filter(_.id.inSetBind(ids)).delete
      val insertAll = table ++= rows
      delete.flatMap(_ => insertAll)
    }.transactionally
    db.run(action).map(_ => ())
  }

}
